import java.util.Comparator;
import java.util.HashSet;
import java.util.TreeMap;
import java.util.TreeSet;

public class Solution881 {
    public int numRescueBoats(int[] people, int limit) {
        TreeMap<Integer, Integer> set = new TreeMap<>();
        for (int person:people) {
            set.put(person, set.getOrDefault(person, 0)+1);
        }
        int boatCount = 0;
        while(true){
            int left = limit;
            for(int i = 0 ; i < 2 ; i++){
                if(left <= 0){
                    break;
                }
                Integer next = set.floorKey(left);
                if(next == null){
                    break;
                }
                left = left - next;
                int count = set.get(next)-1;
                if(count == 0){
                    set.remove(next);
                }
                else {
                    set.put(next, count);
                }
            }
            boatCount++;
            if(set.isEmpty()){
                break;
            }
        }
        return boatCount;
    }

    public static void main(String[] args) {
        Solution881 s = new Solution881();
        System.out.println(s.numRescueBoats(new int[]{3,2,3,2,2},
        6));
    }
}
